package br.embedded.socialapp.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.embedded.socialapp.data.DataFacade;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doLogin(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doLogin(request, response);
	}
	
	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String login = request.getParameter("login");
		String passwd = request.getParameter("passwd");
		
		String[] parameters = {login, passwd};

		if (validateParameters(parameters))
		{
			if (DataFacade.getInstance().doLogin(login, passwd))
			{
				response.sendRedirect("/SocialNetsApp/getting-started.jsp");
			}
		}
		
		writeError(response);
	}

	private void writeError(HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.append("<html>");
		writer.append("<body>");
		writer.append("ERROR");
		writer.append("</body>");
		writer.append("</html>");
	}
	
	private boolean validateParameters(String[] params)
	{
		for (String param : params) {
			if (param == null || param.isEmpty())
				return false;
		}
		return true;
	}
}
